﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.SharePoint.WebControls;
using net.windward.util;
using log4net;

namespace ArrowWebParts
{
    public interface IDashboardProvider
    {
        Dictionary<string, string> VariableValues { get; }
    }
    public class DashboardControllerWebPart : WebPart, IDashboardProvider
    {
        #region fields

        string dataSource = "";
        [Personalizable(PersonalizationScope.User),
       WebBrowsable(false)]
        public string DataSource
        {
            get { return dataSource; }
            set { dataSource = value; }
        }

        string selectStatement = "";
        [Personalizable(PersonalizationScope.User),
       WebBrowsable(false)]
        public string SelectStatement
        {
            get { return selectStatement; }
            set { selectStatement = value; }
        }

        private SPGridView grdItems;
        private DataView view;

        //Repeater controllerView;

        #endregion

        private Dictionary<string, string> variableValues = new Dictionary<string, string>();
        /// <summary>
        /// the log
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(DashboardControllerWebPart));

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (log.IsDebugEnabled)
                log.Debug("creating child controls");

            try
            {
                // read in license from web.config
                ArrowUtils.InitializeArrow(string.Concat(Page.Request.PhysicalApplicationPath, "\\web.config"));
            }
            catch (LicenseException lex)
            {
                ArrowUtils.LogFatalException(log, lex);
                Controls.Add(new LiteralControl(string.Format("License Error: {0}", lex.Message)));
                return;
            }

            try
            {
                // Insert GridView equivalent here...
                SqlConnection conn = new SqlConnection(DataSource);
                SqlCommand cmd = new SqlCommand(SelectStatement, conn);

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable result = new DataTable();
                adapter.Fill(result);
                view = new DataView(result);

                SPBoundField[] boundFields = new SPBoundField[view.Table.Columns.Count];

                grdItems = new SPGridView();
                grdItems.AutoGenerateColumns = false;
                grdItems.AutoGenerateSelectButton = true;
                grdItems.SelectedIndexChanged += new EventHandler(grdItems_SelectedIndexChanged);
                for (int i = 0; i < view.Table.Columns.Count; i++)
                {
                    boundFields[i] = new SPBoundField();
                    boundFields[i].HeaderText = view.Table.Columns[i].ColumnName;
                    boundFields[i].DataField = view.Table.Columns[i].ColumnName;
                    grdItems.Columns.Add(boundFields[i]);
                }
                grdItems.DataSource = view;
                grdItems.DataBind();
                Controls.Add(grdItems);

                //controllerView = new Repeater();
                //controllerView.HeaderTemplate = new ParameterTemplate(ListItemType.Header);
                //controllerView.ItemTemplate = new ParameterTemplate(ListItemType.Item);
                //controllerView.FooterTemplate = new ParameterTemplate(ListItemType.Footer);
                //controllerView.ItemDataBound += new RepeaterItemEventHandler(controllerView_ItemDataBound);
                //controllerView.DataSource = view;
                //controllerView.DataBind();
                //Controls.Add(controllerView);

                //Controls.Add(new LiteralControl("^^^" + grdItems.Rows.Count.ToString() + "^^^"));

                // set variable values to first row
                if (grdItems.Rows.Count > 0)
                {
                    /*for (int i = 0; i < grdItems.SelectedRow.Cells.Count; i++)
                    {
                        variableValues.Add(grdItems.HeaderRow.Cells[i].Text.Trim(), grdItems.SelectedRow.Cells[i].Text.Trim());
                    }*/
                }
            }
            catch(Exception e)
            {
                Controls.Clear();
                Controls.Add(new LiteralControl("Error querying data: " + e.Message));
                ArrowUtils.LogFatalException(log, e);
                return;
            }

            if (log.IsDebugEnabled)
                log.Debug("Finished creating child controls.");
        }

        void grdItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling grid items selected index changed");

            if (grdItems.Rows.Count > 0)
            {
                for (int i = 1; i < grdItems.SelectedRow.Cells.Count; i++)
                {
                    //Label lbl = (Label) grdItems.SelectedRow.Cells[i]
                    variableValues.Add(grdItems.HeaderRow.Cells[i].Text.Trim(), ((Label)grdItems.SelectedRow.Cells[i].Controls[0]).Text.Trim());
                    //Controls.Add(new LiteralControl("^^^" + grdItems.HeaderRow.Cells[i].Text.Trim() + "^^^" + grdItems.SelectedRow.Cells[i].Text.Trim() + "^^^"));
                    //Controls.Add(new LiteralControl("^^^" + grdItems.HeaderRow.Cells[i].Text.Trim() + "***" + ((Label)grdItems.SelectedRow.Cells[i].Controls[0]).Text.Trim() + "^^^"));
                }
            }
            //Controls.Add(new LiteralControl("^^^" + grdItems.SelectedRow.Cells.Count.ToString() + "^^^"));
            //Controls.Add(new LiteralControl("^^^" + grdItems.Rows.Count.ToString() + "^^^"));
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            base.RenderContents(writer);
        }

        public Dictionary<string, string> VariableValues
        {
            get { return this.variableValues; }
        }

        [ConnectionProvider("Dashboard Variables", AllowsMultipleConnections = true)]
        public IDashboardProvider GetDashboardProvider()
        {
            return this;
        }

        public override EditorPartCollection CreateEditorParts()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating editor parts.");

            try
            {
                List<EditorPart> editorParts = new List<EditorPart>(1);
                EditorPart part = new DashboardControllerEditorPart();
                part.ID = this.ID + "_dashboardControllerEditor";
                editorParts.Add(part);
                EditorPartCollection baseParts = base.CreateEditorParts();

                if (log.IsDebugEnabled)
                    log.Debug("Finished creating editor parts.");

                return new EditorPartCollection(baseParts, editorParts);
            }
            catch (Exception ex)
            {
                ArrowUtils.LogFatalException(log, ex);
                throw;
            }
        }
    }
}
